package com.furongji.education.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.furongji.common.enums.OrderStatusEnum;
import com.furongji.common.exception.MyException;
import com.furongji.education.clients.CourseFeignClient;
import com.furongji.education.config.AlipayConfiguration;
import com.furongji.education.domain.po.Order;
import com.furongji.education.domain.po.Pay;
import com.furongji.education.mapper.PayMapper;
import com.furongji.education.service.OrderService;
import com.furongji.education.service.PayService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付表 服务实现类
 * </p>
 *
 * @author furongji
 * @since 2025-05-29
 */
@Service
@RequiredArgsConstructor
public class PayServiceImpl extends ServiceImpl<PayMapper, Pay> implements PayService {

    private final AlipayConfiguration alipayConfig;

    private final OrderService orderService;

    private final CourseFeignClient courseClient;

    // 生成支付宝二维码
    @Override
    public String createQRCode(String orderId) throws AlipayApiException {
        Order order = orderService.getById(orderId);
        if (order == null) {
            throw new MyException(20001, "订单不存在");
        }
        if (order.getStatus().equals(OrderStatusEnum.PAID)) {
            throw new MyException(20001, "订单已支付");
        }

        String qrCode = alipayConfig.precreatePay(order);
        return qrCode;
    }

    @Override
    @Transactional
    public String handleAlipayNotify(HttpServletRequest request) throws AlipayApiException {
        Map<String, String> params = new HashMap<>();
        request.getParameterMap().forEach((String key, String[] values) -> {
            if (values.length > 0) {
                params.put(key, values[0]);
            }
        });
        boolean verified = AlipaySignature.rsaCheckV1(
                params,
                alipayConfig.getAlipayPublicKey(),
                alipayConfig.getCharset(),
                alipayConfig.getSignType()
        );
        if (!verified) {
            // 验签失败，拒绝通知
            return "failure";
        }

        String tradeStatus = params.get("trade_status");
        if (!"TRADE_SUCCESS".equals(tradeStatus) && !"TRADE_FINISHED".equals(tradeStatus)) {
            // 不是成功状态，不处理
            return "failure";
        }

        String orderId = params.get("out_trade_no");

        if (StringUtils.isEmpty(orderId)) {
            System.err.println("订单号为空.....");
        }

        Order order = orderService.getById(orderId);

        if (order == null) {
            // 订单不存在
            return "failure";
        }

        if (order.getStatus().equals(OrderStatusEnum.PAID)) {
            // 订单已经支付过了，直接返回成功，防止支付宝重复通知
            return "已经支付过了";
        }

        order.setStatus(OrderStatusEnum.PAID);
        orderService.updateById(order);

        // TODO 后续改用RabbitMQ
        String courseId = order.getCourseId();
        courseClient.buyCourseCount(courseId);

        Pay pay = new Pay();
        pay.setOrderId(order.getId());
        pay.setPayPrice(order.getTotalPrice());
        pay.setTradeState("SUCCESS");
        super.save(pay);
        return "success";
    }
}
